package 七大排序;

import com.sun.scenario.effect.impl.sw.java.JSWColorAdjustPeer;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author 一哑7
 * @date 2022/03/15 19:39
 * 生成排序数组的辅助测试类
 **/
//根据传入的方法名就可以调用方法，借助反射
public class 生成测试数组 {
    //final修饰对象，内容可变引用不可变
    public static final ThreadLocalRandom random = ThreadLocalRandom.current();
    public static void testSort(String sortName , int[] arr){
        Class<七大排序> cls = 七大排序.class;
        try {
            Method method = cls.getMethod(sortName , int[].class);
            Long startTime = System.nanoTime();
            method.invoke(null , arr);
            Long endTime = System.nanoTime();
            if (isSort(arr)){
                System.out.println(sortName + "算法共耗时：" + (endTime - startTime) / 1000000 + "ms");
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    public static boolean isSort(int[] arr){
        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i] > arr[i + 1]){
                System.out.println("没排序好");
                return false;
            }
        }
        return true;
    }
    //生成无序数组
    public static int[] disorderArr(int n , int left , int right){//n个元素，范围[left , right)
        int[] arr = new int[n];
        for (int i = 0; i < arr.length - 1; i++) {
            arr[i] = random.nextInt(left  , right);
        }
        return arr;
    }
    //生成有序数组
    public static int[] orderlyArr(int n , int times){//n个元素(0 - n) ， 复杂度（times）即交换times次
        int[] arr = new int[n];
        for (int i = 0; i < arr.length - 1; i++) {
            arr[i] = i;
        }
        for (int i = 0; i < times; i++) {
            int a = random.nextInt(n);//交换的是数组内的值，此时a，b指的依然是索引
            int b = random.nextInt(n);
            swap(arr , a , b);
        }
        return arr;
    }
    public static void swap(int[] arr , int i , int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[i] = temp;
    }
    public static int[] copyOf(int[] arr){
        int[] arrCopyOf = Arrays.copyOf(arr , arr.length);//复制数组，深拷贝
        return arrCopyOf;
    }

}

